package com.bwie.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.dto.UserPwdVo;
import com.bwie.vo.UserVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    //注入userMapper
    @Autowired
    private UserMapper userMapper;

    //注入 Redis
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public R pwdLogin(UserPwdVo userVo) {
        //1、密码进行加密 使用 MD5
        String encryptPwd = MD5Utils.encrypt(userVo.getPassword());
        //2、
        User user = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getAccount, userVo.getAccount())
        );
        if (ObjectUtils.isEmpty(user)){
            return R.ERROR(-1,"账户不存在，请注册");
        }
        if (!user.getPassword().equals(encryptPwd)){
            return R.ERROR(-1,"账户或密码错误");
        }
        //3、生成 token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie")
                .claim("userId", user.getUserId())
                .claim("userName", user.getUserName())
                .compact();

        //4、redis 存储 token 时间 5 分钟 注意 key 值 为活值
        String tokenKey = "token:"+user.getUserId();
        redisTemplate.opsForValue().set(tokenKey,token,5, TimeUnit.MINUTES);

        HashMap<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);

        return R.OK(map);
    }

    @Override
    public R selectUserInfoById(Integer userId) {
        User user = userMapper.selectById(userId);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user,userVo);
        return R.OK(userVo);
    }
}
